package com.ymh.spring.learn.mq.rabbitmq;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.ConsumerCancelledException;
import com.rabbitmq.client.QueueingConsumer;
import com.rabbitmq.client.QueueingConsumer.Delivery;
import com.rabbitmq.client.ShutdownSignalException;

/**
 * 
 * 名称：Received<br/>
 * 描述：消息接收端<br/>
 * 创建时间：2018年4月9日 下午6:28:46 <br/>
 * 
 * @author aivin
 * @version 1.0.0
 */
public class Received {

	private static final String QUEUE_NAME = "test";

	public static void main(String[] args) throws IOException, TimeoutException, ShutdownSignalException, ConsumerCancelledException, InterruptedException {
		// 创建连接连接到RabbitMQ
		ConnectionFactory connectionFactory = new ConnectionFactory();
		// 设置RabbitMQ所在的IP或者主机名
		connectionFactory.setHost("localhost");
		// 创建一个连接
		Connection connection = connectionFactory.newConnection();
		// 通过连接创建一个频道
		Channel channel = connection.createChannel();
		// 声明队列，主要是为了防止消息接收者先运行此程序，队列还不存在时创建队列。
		channel.queueDeclare(QUEUE_NAME, false, false, false, null);
		System.out.println("[*] Waiting for messages.");

		// 创建队列消费者
		QueueingConsumer consumer = new QueueingConsumer(channel);
		// 指定消费队列
		channel.basicConsume(QUEUE_NAME, true, consumer);
		while (true) {
			//nextDelivery()是一个阻塞方法（内部实现其实是阻塞队列的take方法）
			Delivery delivery = consumer.nextDelivery();
			String message = new String(delivery.getBody());
			System.out.println("[x]Received" + message);
		}

	}

}
